package com.example.mq.mqserver.datacenter;

import com.example.mq.MqApplication;
import com.example.mq.mqserver.core.Binding;
import com.example.mq.mqserver.core.Exchange;
import com.example.mq.mqserver.core.ExchangeType;
import com.example.mq.mqserver.core.MSGQueue;
import com.example.mq.mqserver.mapper.MetaMapper;

import java.io.File;
import java.util.List;

public class DataBaseManger {
    private MetaMapper mapper;

    public void init(){
        mapper = MqApplication.context.getBean(MetaMapper.class);
        if(!checkDBExists()){
            //数据库不存在就进行数据库建表操作
            File fileDir = new File("./data");
            fileDir.mkdirs();
            createTable();
            createDefaultData();
            System.out.println("[DataBaseManger] 数据库初始化完成");
        }else{
            System.out.println("[DataBaseManger] 数据库已存在");
        }
    }

    private void createDefaultData() {
        Exchange exchange = new Exchange();
        exchange.setName("");
        exchange.setType(ExchangeType.DIRECT);
        exchange.setDurable(true);
        exchange.setAutoDelete(false);
        mapper.insertExchange(exchange);
        System.out.println("[DataBaseManger] 数据已成功插入exchange");
    }

    private void createTable() {
        mapper.createExchangeTable();
        mapper.createQueueTable();
        mapper.createBindingTable();
        System.out.println("[DataBaseManger] 数据库已经成功建表");
    }

    private boolean checkDBExists() {
        File file = new File("./data/meta.db");
        if(file.exists()){
            return true;
        }
        return false;
    }

    public void insertExchange(Exchange exchange){
        mapper.insertExchange(exchange);
    }

    public void deleteExchange(String exchangeName){
        mapper.deleteExchange(exchangeName);
    }

    public List<Exchange> selectAllExchange(){
        return mapper.selectAllExchange();
    }

    public void insertQueue(MSGQueue queue){
        mapper.insertQueue(queue);
    }

    public void deleteQueue(String queueName){
        mapper.deleteQueue(queueName);
    }

    public List<MSGQueue> selectAllQueue(){
        return mapper.selectAllQueue();
    }

    public void insertBinding(Binding binding){
        mapper.insertBinding(binding);
    }

    public void deleteExchange(Binding binding){
        mapper.deleteBinding(binding);
    }

    public List<Binding> selectAllBinding(){
        return mapper.selectAllBinding();
    }

    public void deleteDB() {
        File file = new File("./data/meta.db");
        if (file.delete()){
            System.out.println("[DataBaseManger] 数据库已经成功删除");
        }else {
            System.out.println("[DataBaseManger] 数据库目录失败");
        }
        File fileDir = new File("./data");
        if (fileDir.delete()){
            System.out.println("[DataBaseManger] 数据库目录已经成功删除");
        }else {
            System.out.println("[DataBaseManger] 数据库目录删除失败");
        }
    }
}
